package com.mlming.springboot.controller;

import com.github.pagehelper.PageInfo;
import com.mlming.springboot.consts.MallConst;
import com.mlming.springboot.form.ShippingForm;
import com.mlming.springboot.pojo.User;
import com.mlming.springboot.service.ShippingService;
import com.mlming.springboot.util.JWTUtil;
import com.mlming.springboot.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Map;

@RestController
public class ShippingController {
    @Autowired
    private ShippingService shippingService;

    @PostMapping("/shippings")
    public ResponseVo<Map<String,Integer>> addShipping(HttpServletRequest request,
                                                       @Valid @RequestBody ShippingForm shippingForm) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return shippingService.addShipping(userId,shippingForm);
    }

    @DeleteMapping("/shippings/{shippingId}")
    public ResponseVo deleteShipping(HttpServletRequest request,
                                     @PathVariable Integer shippingId) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return shippingService.deleteShipping(userId,shippingId);
    }

    @PutMapping("/shippings/{shippingId}")
    public ResponseVo updateShipping(HttpServletRequest request,
                                     @PathVariable Integer shippingId,
                                     @Valid @RequestBody ShippingForm shippingForm) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return shippingService.updateShipping(userId,shippingId,shippingForm);
    }

    @GetMapping("/shippings")
    public ResponseVo<PageInfo> getShippingList(HttpServletRequest request,
                                                @RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false,defaultValue = "10") Integer pageSize) {
        String token = request.getHeader(MallConst.TOKEN_NAME);
        Integer userId = Integer.valueOf(JWTUtil.getFieldValuePayLoad(token, MallConst.USER_ID_IN_PAYLOAD));
        return shippingService.getShippingList(userId,pageNum,pageSize);
    }
}
